#!/usr/bin/env bash

function red() {
  echo -e "\033[0;31m$1\033[0m"
}
function green() {
  echo -e "\033[0;32m$1\033[0m"
}
function yellow() {
  echo -e "\033[0;33m$1\033[0m"
}

HEROKU_APP=$1
HEROKU_RELEASES=`heroku releases --app $HEROKU_APP 2>&1`
GIT_COMMAND=${GIT_COMMAND:="git push git@heroku.com:$HEROKU_APP.git $SHA:master $GIT_FLAGS"}
POST_MIGRATION_DEPLOY=${POST_MIGRATION_DEPLOY:="true"}

if [[ -z "${HEROKU_APP}" ]]; then
  red "Usage: $0 <app-name>"
  red "Supported environment variables:"
  red "  - GIT_COMMAND: override the entire 'git push' command."
  red "  - GIT_FLAGS: add arguments to the default 'git push' command."
  exit 1;
fi

echo "$HEROKU_RELEASES" | grep 'Current: \(v[0-9]\+\)' >/dev/null

if [[ $? -ne 0 ]]; then
  red "Error detecting current heroku release. Message from 'heroku releases':"
  echo "${HEROKU_RELEASES}"
  red "Please contact a heroku collaborator for ${HEROKU_APP}:"
  heroku access --app $HEROKU_APP
  exit 1;
fi

HEROKU_LAST_GOOD_RELEASE=`echo "$HEROKU_RELEASES" | grep 'Current: \(v[0-9]\+\)' | sed -e 's/.*\(v[0-9]\+\).*/\1/'`
green "Current heroku release: ${HEROKU_LAST_GOOD_RELEASE}"

green "Pushing to heroku."
$GIT_COMMAND
if [[ $? -ne 0 ]]; then
  red "Heroku push rejected. See message above."
  red "Please contact a heroku collaborator for ${HEROKU_APP}:"
  heroku access --app $HEROKU_APP
  exit 1;
fi

MIGRATION_STATUS=`heroku run rake db:migrate:status --app $HEROKU_APP | grep -e '^\s*down'`

if [[ "${MIGRATION_STATUS}" != "" ]]; then
  green "There are pending migrations to apply:"
  echo $MIGRATION_STATUS

  green "Migrating database."
  heroku run rake db:migrate --app $HEROKU_APP

  POST_MIGRATION_STATUS=`heroku run rake db:migrate:status --app $HEROKU_APP | grep -e '^\s*down'`
  if [[ "${POST_MIGRATION_STATUS}" != "" ]]; then
    red "Migration failed! This is bad."
    red "Please contact a heroku collaborator for ${HEROKU_APP}:"
    heroku access --app $HEROKU_APP
    red "The app ${HEROKU_APP} will now be reverted to its last working version ${HEROKU_LAST_GOOD_RELEASE}."
    heroku releases:rollback $HEROKU_LAST_GOOD_RELEASE --app $HEROKU_APP
    red "Abort."
    exit 1
  fi

  if [[ "${POST_MIGRATION_DEPLOY}" == "true" ]]; then
    green "Post-migration dyno restart."
    heroku restart --app $HEROKU_APP
  fi
else
  green "There are no pending migrations."
fi

green "All done."
